import type { Form, ISchema } from '@minmetals-ui/pro-components';
import type { ElTable } from 'element-plus-cisdi';
import type { AssignPropEmits, DefaultRow, QueryConditionProps, QueryConditionSchema, RecordType } from '../types/QueryCondition';
import { ElMessage } from 'element-plus-cisdi';

import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';

export function UseRoleDialog(props: QueryConditionProps, emits: AssignPropEmits) {
  const { t } = useI18n();
  const {
    grid = {
      minColumns: 3,
      maxColumns: 3,
      labelCol: 6,
      wrapperCol: 10,
    },
    queryAssignUser,
  } = props;
  const formRef = ref<{ form: Form }>();
  const inputValue = ref('');
  const tableRef = ref<InstanceType<typeof ElTable> | null>(null);
  const pagination = computed(() => props.pageData);
  // 替换原来的 const reactiveTableData = computed(() => props.tableData)
  const reactiveTableData = ref<RecordType[]>([]);

  const dialogVisible = computed(() => props.dialogVisible);
  const schema = ref<ISchema | undefined>(undefined);

  watch(() => props.tableData, (val) => {
    reactiveTableData.value = val || [];
  }, { deep: true });

  watch(() => props.queryCondition, (val) => {
    const properties = transformQueryCondition(val);
    schema.value = {
      type: 'object',
      properties: {
        grid: {
          'type': 'void',
          'x-component': 'FormGrid',
          'x-component-props': grid,
          'properties': properties,
        },
      },
    };
  }, { deep: true });

  function initFormRef(ref: any) {
    formRef.value = ref;
  }

  function transformQueryCondition(data: QueryConditionSchema[]) {
    const result: Record<string, ISchema> = {};
    data.forEach((item) => {
      result[item.field] = {
        'type': 'string',
        'title': item.fieldTitle,
        'x-decorator': 'FormItem',
        'x-decorator-props': item.fieldItemProps || { labelCol: 4, wrapperCol: 20 },
        'x-component': item.fieldComponent,
        'x-component-props': item.fieldProps,
        'x-validator': item.fieldValidator,
        'x-reactions': item.fieldReactions,
        'default': item.defaultValue,
      };
    });
    return result;
  }

  function handleDelete(index: number, row: DefaultRow) {
    emits('deleteUser', [row?.id]);
  }

  function closeDialog() {
    inputValue.value = '';
    emits('closeDialog');
  }

  function saveData() {
    // ElMessage.success('保存成功')
    closeDialog();
  }

  function deleteUsers() {
    const rows = tableRef.value?.getSelectionRows();
    if (rows?.length) {
      const selectedIds = rows.map((item: DefaultRow) => item.id);
      reactiveTableData.value = reactiveTableData.value.filter(item => !selectedIds.includes(item.id));
      emits('deleteUser', selectedIds);
    } else {
      ElMessage.warning(t('roleManage.placeholder.deleteSelect'));
    }
  }

  function openAddAssignUser() {
    emits('openAddAssignUser');
  }

  function handleEnter() {
    queryAssignUser && queryAssignUser({
      current: pagination.value.current,
      size: pagination.value.size,
      roleId: props?.assignModelValue?.roleId,
      search: inputValue.value,
      orgCode: props?.assignModelValue?.roleOrgCode,
    });
  }

  return {
    tableRef,
    schema,
    formRef,
    initFormRef,
    pagination,
    handleDelete,
    tableData: reactiveTableData,
    closeDialog,
    saveData,
    dialogVisible,
    deleteUsers,
    openAddAssignUser,
    handleEnter,
    inputValue,
  };
}
